﻿using Book.Data;
using Book.Entities;
using Book.IRepositories;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace Book.Repositiories
{
    public class MenuRepository : IMenuRepository
    {
        private readonly BookDbContext _DbContext;

        public MenuRepository(BookDbContext bookDbContext)
        {
            this._DbContext = bookDbContext;
        }
        /// <summary>
        /// 获得所有菜单Json
        /// </summary>
        /// <returns></returns>        
        public List<MenuEntity> GetMenuJson()
        {
            List<MenuEntity> MenuLists = _DbContext.menu.OrderBy(x => x.Order).ToList();//从数据库获得所有菜单
            //List<SecondaryMenuEntity> SecondaryMenusLists = _DbContext.secondaryMenu.ToList();
            /*List<AllMenuEntity> AllMenuLists = new List<AllMenuEntity>();*/
            /*foreach (var item in SecondaryMenusLists)
            {
                MenuLists.Add(new MenuEntity { 
                Id=item.Id,
                ParentId=item.ParentId,
                EName=item.EName,
                Name=item.Name,
                Order=item.Order,
                Template=item.Template,
                Url=item.Url
                });
            }*/
            //AllMenuLists.Add(MenuLists);
            //创建一个javascriptserializer对象
            //JavaScriptSerializer serializer = new JavaScriptSerializer();
            //将用户列表序列化成json
            //String serializedresult = serializer.Serialize(MenuLists);
            /*String serializedresult2 = serializer.Serialize(SecondaryMenusLists);
            var resultJson = serializer.Serialize(new { Serializedresult = serializedresult, Serializedresult2 = serializedresult2 });*/
            return MenuLists;
        }
        public List<MenuEntity> GetTreeJson()
        {           
            BindTree(null, null);
            //string str = JsonConvert.SerializeObject(treeNodes);
            return treeNodes;            
        }              
        public List<MenuEntity> treeNodes = new List<MenuEntity>();
        public void BindTree( MenuEntity parentNode, string PId)
        {         
            List<MenuEntity> MenuLists = _DbContext.menu.
                OrderBy(x=>x.Order)
                .ToList();//从数据库获得所有菜单
            var q = MenuLists.Where(x => x.ParentId == PId).ToList();
            foreach (var item in q)
            {
                MenuEntity tree = new MenuEntity();
                tree.Name = item.Name;
                tree.Id = item.Id;
                //递归性质，函数内调用自身函数
                BindTree(tree, tree.Id);
                //递归结束的终点条件
                if (parentNode == null)
                {
                    treeNodes.Add(tree);
                }
                else
                {
                    parentNode.Childrens.Add(tree);
                }
            }
            
        }
        /// <summary>
        /// 根据id获得菜单列表
        /// </summary>
        /// <returns></returns>
        public List<MenuEntity> GetMenuByPId(string id)
        {
            List<MenuEntity> MenuLists = _DbContext.menu.OrderBy(x => x.Order).ToList();
            List<MenuEntity> MenuListsByPId = new List<MenuEntity>();
            string parentid = _DbContext.menu.Find(id).ParentId;
            if (parentid==null)
            {
                foreach (var item in MenuLists)
                {
                    if (item.Id==id) { 
                    MenuListsByPId.Add(new MenuEntity
                    {
                        Id = item.Id,
                        ParentId = item.ParentId,
                        EName = item.EName,
                        Name = item.Name,
                        Order = item.Order,
                        Template = item.Template,
                        Url = item.Url
                    });}
                    if (item.ParentId == id)
                    {
                        MenuListsByPId.Add(new MenuEntity
                        {
                            Id = item.Id,
                            ParentId = item.ParentId,
                            EName = item.EName,
                            Name = item.Name,
                            Order = item.Order,
                            Template = item.Template,
                            Url = item.Url
                        });
                    }
                }
            }
            if (parentid != null)
            {
                foreach (var item in MenuLists)
                {
                    if (item.Id == parentid)
                    {                    
                        MenuListsByPId.Add(new MenuEntity
                        {
                            Id = item.Id,
                            ParentId = item.ParentId,
                            EName = item.EName,
                            Name = item.Name,
                            Order = item.Order,
                            Template = item.Template,
                            Url = item.Url
                        });
                    }
                    if (item.ParentId == parentid)
                    {
                        MenuListsByPId.Add(new MenuEntity
                        {
                            Id = item.Id,
                            ParentId = item.ParentId,
                            EName = item.EName,
                            Name = item.Name,
                            Order = item.Order,
                            Template = item.Template,
                            Url = item.Url
                        });
                    }
                }
            }
            
            return MenuListsByPId;
        }
        /// <summary>
        /// 获得一条菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public MenuEntity GetOneMenuById(string id) {
            MenuEntity menuentity = _DbContext.menu.Find(id);
            return menuentity;
        }

        /// <summary>
        /// 添加菜单测试用
        /// </summary>
        /// <param name="menu"></param>
        public void AddMenu1(MenuEntity menu)
        {
            MenuEntity menuEntity = new MenuEntity
            {
                Name = menu.Name,
                EName = menu.EName,
                Order = menu.Order,
                ParentId = menu.ParentId,
                Template = menu.Template,
            };
            _DbContext.menu.Add(menu);
            _DbContext.SaveChanges();
        }
        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <param name="name"></param>
        /// <param name="ename"></param>
        /// <param name="url"></param>
        /// <param name="template"></param>
        /// <param name="parentid"></param>
        public void AddMenu(string name,string ename, int template, string parentid)
        {
            if (parentid == null)
            {
                List<MenuEntity> MenuLists = _DbContext.menu.
                OrderBy(x => x.Order)
                .ToList();//从数据库获得所有菜单
                double order = MenuLists.Count;
                MenuEntity menuEntity = new MenuEntity
                {
                    Id = Guid.NewGuid().ToString("N").Substring(0, 29),
                    Name = name,
                    EName = ename,
                    Order = order,
                    ParentId = parentid,
                    Template = (Enum.TemplateEnum)template,

                };
                _DbContext.menu.Add(menuEntity);
                _DbContext.SaveChanges();
            }
            else 
            {
                List<MenuEntity> MenuLists = _DbContext.menu.OrderBy(x => x.Order).Where(x=>x.ParentId==parentid||x.Id==parentid).ToList();
                double order = MenuLists.Last().Order + 0.5;
                MenuEntity menuEntity = new MenuEntity
                {
                    Id = Guid.NewGuid().ToString("N").Substring(0, 29),
                    Name = name,
                    EName = ename,
                    Order = order,
                    ParentId = parentid,
                    Template = (Enum.TemplateEnum)template,

                };
                _DbContext.menu.Add(menuEntity);
                _DbContext.SaveChanges();
            }
            Reorder();
            
        }
        public void UpdateMenu(string name, string ename, int template, string id)
        {
            //double  order = _DbContext.menu.Find(id).Order;
            //int? parentid = _DbContext.menu.Find(id).ParentId;
            MenuEntity menuEntity = _DbContext.menu.Find(id);
            menuEntity.Name = name;
            menuEntity.EName = ename;               
            menuEntity.Id = id;
            menuEntity.Template = (Enum.TemplateEnum)template;            
            _DbContext.menu.Update(menuEntity);
            _DbContext.SaveChanges();
        }
        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="id"></param>
        public bool DeleteMenu(string id)
        {
            //MenuEntity menuEntity = new MenuEntity { Id = id };
            MenuEntity menuEntity = _DbContext.menu.Find(id);
            if (menuEntity.ifdelete == true)
            {
                return false;
            }
            else 
            {
                _DbContext.menu.Remove(menuEntity);
                _DbContext.SaveChanges();
                Reorder();
                return true;
            }
            
        }
        /// <summary>
        /// 修改菜单
        /// </summary>
        /// <param name="menu"></param>
        public void UpdateMenu(MenuEntity menu)
        {            
            _DbContext.menu.Update(menu);
            _DbContext.SaveChanges();

        }
        public void UpdateOrder(string id, string pid, double order)
        {
            MenuEntity menuEntity = _DbContext.menu.Find(id);
            menuEntity.ParentId = pid;
            menuEntity.Order = order;
            _DbContext.menu.Update(menuEntity);
            _DbContext.SaveChanges();
            Reorder();
        }
        public void Reorder()
        {
            List<MenuEntity> MenuLists = _DbContext.menu.
                OrderBy(x => x.Order)
                .ToList();//从数据库获得所有菜单
            for (int i = 0; i < MenuLists.Count; i++) 
             {
                MenuLists[i].Order = i;
                _DbContext.menu.Update(MenuLists[i]);
                _DbContext.SaveChanges();
            }            
        }
    }
}